package com.fbooks.utils.email.Impl;

import com.fbooks.bean.Email;
import com.fbooks.utils.email.AccountEmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * @Author: LuoRunFeng
 * @e-mail: 475403147@qq.com
 * @Time: 2020/4/27 13:34
 * @Version 1.0
 */
@Component
@PropertySource("classpath:email.properties")
public class AccountEmailServiceImpl implements AccountEmailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TaskExecutor taskExecutor;

//    @Resource
//    private SimpleMailMessage preConfiguredMessage;

    @Value("${email.systemEmail}")
    private String systemEmail;


    /**
     *  同步发送
     * @param email
     * @throws AccountEmailException
     */
    public void sendMail(Email email) throws AccountEmailException {
        Session session= Session.getDefaultInstance(new Properties());
        MimeMessage mime= new MimeMessage(session);
        try{
            MimeMessageHelper msgHelper = new MimeMessageHelper(mime, true, "utf-8");
            msgHelper.setFrom(systemEmail);
            msgHelper.setTo(email.getAddressee());
            msgHelper.setSubject(email.getSubject());
            msgHelper.setText(email.getContent(), true);

            javaMailSender.send(mime);
        }catch (MessagingException e){
            throw new AccountEmailException("AccountEmailServiceImpl:邮件发送失败", e);
        }
    }

    /**
     * 异步发送
     * @param email
     */
    public void sendMailByAsynchronousMode(final Email email){
        taskExecutor.execute(new Runnable() {
            public void run() {
                try{
                    sendMail(email);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 生成验证码
     * @param str
     * @param length
     * @return
     */
    public String createCaptchaCode(String str,Integer length){

        String randomStr = "";
        List<String> radomStrList = Arrays.asList(str.split(""));
        Collections.shuffle(radomStrList);
        for (String s : radomStrList) {
            randomStr+=s;
        }
        String captchaCode = randomStr.substring(0,length);
        return captchaCode;
    }
}
